var { WebSocketServer } = require('ws');
const queryString =require('querystring');
const wss1 = new WebSocketServer({ noServer: true });

wss1.on('connection',function(ws,request,socketKey){
        const ip = request.connection.remoteAddress;
        //const ip2 = request.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
        var headers=JSON.stringify(request.headers);
        console.log(`connection,ip:${ip},headers:${headers}`); 
        ws.isAlive=true;
        ws.ip=ip;
        ws.keyId=socketKey;
        ws.on('pong',heartbeat);
        ws.on('message',(data)=>{  
            console.log(JSON.stringify(data));
            console.log(Buffer.isBuffer(data));
            console.log(typeof(data.toString('utf8')));
            console.log(data.toString('utf8') instanceof String);
            const mes=data.toString('utf8');
            if(mes.includes('^')){
                return sendAt(mes,ws);
            }
            ws.send(ws.keyId+' 说：'+mes);
           
            //console.log(`Received message ${data} from user ${request}`);
        });    
});
function sendAt(mes,myself){
    const user=mes.split('^')[0];
    const meg=mes.split('^')[1];
    myself.send(myself.keyId+' 说：'+mes);
    if(user.includes('@')){
        const userKeys=user.split("@");
        console.log("userKeys:"+userKeys);
        wss1.clients.forEach((client)=>{
            if(userKeys.includes(client.keyId)){
                client.send(myself.keyId+"对你说："+meg);
            }
        })
    }
}
const interval = setInterval(function ping(){
    wss1.clients.forEach((client)=>{
        console.log('clientKey:',client.keyId);
        if(client.isAlive === false) {
            return client.terminate();
        }
        client.isAlive =false;
        client.ping();
    })
},30000);
function heartbeat(){
    this.isAlive=true;
 }
 wss1.on('close', function close() {
    clearInterval(interval);
  });
module.exports=wss1;